package com.example.cardgame
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.RadioButton
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date

class ModifyInfoActivity : AppCompatActivity() {
    companion object {
        private const val REQUEST_CAMERA_PERMISSION = 100
        private const val CAPTURE_IMAGE_REQUEST = 101
    }
    private lateinit var userInfo: MutableMap<String, String?>
    private lateinit var imageViewAvatar: ImageView
    private lateinit var imageButtonCamera: ImageButton
    private val PICK_IMAGE_REQUEST = 1
    private val CAPTURE_IMAGE_REQUEST = 2
    private lateinit var imageUri: Uri
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.second_activity)
        // 提供一个扩展函数将 Bundle 转换为 MutableMap
        imageViewAvatar = findViewById(R.id.imageViewAvatarEdit)
        imageButtonCamera = findViewById(R.id.imageButtonCamera)

        imageButtonCamera.setOnClickListener {
            openCameraOrGallery() // 打开相机或图库
        }
        fun Bundle.toMutableMap(): MutableMap<String, String?> {
            val map = mutableMapOf<String, String?>()
            for (key in this.keySet()) {
                map[key] = this.getString(key) // 这里假设您只需要字符串
            }
            return map
        }

        // 从Intent获取传递的用户信息
        userInfo = intent.extras?.toMutableMap() ?: mutableMapOf()

        // 初始化UI并填充数据
        initializeUI()

        // 设置保存按钮的点击事件
        val buttonSave = findViewById<Button>(R.id.buttonSave)
        buttonSave.setOnClickListener {
            saveUserInfo()
        }

        // 设置取消按钮的点击事件
        val buttonCancel = findViewById<Button>(R.id.buttonCancel)
        buttonCancel.setOnClickListener {
            finish()  // 直接返回MainActivity
        }
    }
    private fun openCameraOrGallery() {
        val options = arrayOf("相机", "图库")
        val builder = androidx.appcompat.app.AlertDialog.Builder(this)
        builder.setTitle("选择图片来源")
        builder.setItems(options) { dialog, which ->
            when (which) {
                0 -> openCamera() // 从相机拍照
                1 -> openGallery() // 从图库选择
            }
        }
        builder.show()
    }
private fun openCamera() {
    // 检查相机权限
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
        return  // 如果没有权限，则返回，等待用户响应权限请求
    }

    // 如果有权限，则打开相机
    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    if (cameraIntent.resolveActivity(packageManager) != null) {
        val photoFile = createImageFile() // 创建图片文件
        imageUri = FileProvider.getUriForFile(this, "com.example.cardgame.fileprovider", photoFile)
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri) // 将 Uri 提供给相机
        startActivityForResult(cameraIntent, CAPTURE_IMAGE_REQUEST)
    }
}


    // 创建临时文件
private lateinit var currentPhotoPath: String

@Throws(IOException::class)
private fun createImageFile(): File {
    val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
    val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    return File.createTempFile("JPEG_$timeStamp", ".jpg", storageDir).apply {
        currentPhotoPath = absolutePath // 维护当前文件路径
    }
}



    private fun openGallery() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(Intent.createChooser(intent, "选择图片"), PICK_IMAGE_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                PICK_IMAGE_REQUEST -> {
                    val imageUri = data?.data
                    imageViewAvatar.setImageURI(imageUri)
                    userInfo["avatarUri"] = imageUri.toString()
                }
                CAPTURE_IMAGE_REQUEST -> {
                    val bitmap = BitmapFactory.decodeFile(currentPhotoPath)
                    imageViewAvatar.setImageBitmap(bitmap)
                    userInfo["avatarUri"] = imageUri.toString()
                }
            }
        }
    }


override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
    if (requestCode == REQUEST_CAMERA_PERMISSION) {
        if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
            // 权限被授予，可以继续拍照
            openCamera()
        } else {
            // 权限被拒绝，给出提示
        }
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}

    private fun initializeUI() {
        val editTextName = findViewById<EditText>(R.id.editTextNameEdit)
        val editTextStudentID = findViewById<EditText>(R.id.editTextStudentIDEdit)
        val editTextPhone = findViewById<EditText>(R.id.editTextPhoneEdit)
        val editTextEmail = findViewById<EditText>(R.id.editTextEmailEdit)
        val radioButtonMale = findViewById<RadioButton>(R.id.radioButtonMale)
        val radioButtonFemale = findViewById<RadioButton>(R.id.radioButtonFemale)
        val checkBoxTravel = findViewById<CheckBox>(R.id.checkBoxTravel)
        val checkBoxReading = findViewById<CheckBox>(R.id.checkBoxReading)
        val checkBoxGaming = findViewById<CheckBox>(R.id.checkBoxGaming)
        val checkBoxShopping = findViewById<CheckBox>(R.id.checkBoxShopping)

        editTextName.setText(userInfo["name"])
        editTextStudentID.setText(userInfo["studentID"])
        editTextPhone.setText(userInfo["phone"])
        editTextEmail.setText(userInfo["email"])
        radioButtonMale.isChecked = userInfo["gender"] == "男"
        radioButtonFemale.isChecked = userInfo["gender"] == "女"
        checkBoxTravel.isChecked = userInfo["hobbies"]?.contains("旅游") ?: false
        checkBoxReading.isChecked = userInfo["hobbies"]?.contains("阅读") ?: false
        checkBoxGaming.isChecked = userInfo["hobbies"]?.contains("游戏") ?: false
        checkBoxShopping.isChecked = userInfo["hobbies"]?.contains("购物") ?: false

        val avatarUri = userInfo["avatarUri"]
        if (!avatarUri.isNullOrBlank()) {
            imageViewAvatar.setImageURI(Uri.parse(avatarUri))
        }
    }

    private fun saveUserInfo() {
        val editTextName = findViewById<EditText>(R.id.editTextNameEdit)
        val editTextStudentID = findViewById<EditText>(R.id.editTextStudentIDEdit)
        val editTextPhone = findViewById<EditText>(R.id.editTextPhoneEdit)
        val editTextEmail = findViewById<EditText>(R.id.editTextEmailEdit)
        val radioButtonMale = findViewById<RadioButton>(R.id.radioButtonMale)
        val radioButtonFemale = findViewById<RadioButton>(R.id.radioButtonFemale)
        val checkBoxTravel = findViewById<CheckBox>(R.id.checkBoxTravel)
        val checkBoxReading = findViewById<CheckBox>(R.id.checkBoxReading)
        val checkBoxGaming = findViewById<CheckBox>(R.id.checkBoxGaming)
        val checkBoxShopping = findViewById<CheckBox>(R.id.checkBoxShopping)

        // 获取性别
        val gender = if (radioButtonMale.isChecked) "男" else "女"

        // 获取爱好
        val hobbies = listOfNotNull(
            if (checkBoxTravel.isChecked) "旅游" else null,
            if (checkBoxReading.isChecked) "阅读" else null,
            if (checkBoxGaming.isChecked) "游戏" else null,
            if (checkBoxShopping.isChecked) "购物" else null
        ).joinToString(", ")

        // 更新 userInfo 中的基本个人信息字段
        userInfo["name"] = editTextName.text.toString()
        userInfo["gender"] = gender
        userInfo["studentID"] = editTextStudentID.text.toString()
        userInfo["phone"] = editTextPhone.text.toString()
        userInfo["email"] = editTextEmail.text.toString()
        userInfo["hobbies"] = hobbies

        // 不更新 highScore，保留原来的分数
        // userInfo["highScore"] 仍然保持不变

        // 将更新后的 userInfo 放回 Intent
        val intent = Intent()
        userInfo.forEach { (key, value) ->
            intent.putExtra(key, value)
        }

        setResult(RESULT_OK, intent)
        finish()
    }

}